import { defineConfig, ConfigEnv, UserConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
//按需导入element-plus
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";

import unocss from "unocss/vite";
import { presetIcons, presetAttributify, presetUno } from "unocss";

const CWD = process.cwd();
// https://vitejs.dev/config/
/**
 * defineConfig 智能提示
 * @params{command}  情景配置  build | serve
 * @params{mode}  环境模式  development |
 */
export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
  //根据mode加载env文件的环境变量
  const env = loadEnv(mode, process.cwd());
  // 环境变量
  const { VITE_BASE_URL, VITE_DROP_CONSOLE } = loadEnv(mode, CWD);
  return {
    base: VITE_BASE_URL,
    plugins: [
      vue(),
      //按需导入插件
      AutoImport({
        resolvers: [
          ElementPlusResolver(),
          // 自动导入图标组件
          IconsResolver({
            prefix: "Icon",
          }),
        ],
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ["ep"],
          }),
        ],
      }),
      Icons({
        autoInstall: true,
      }),
      unocss({
        presets: [presetIcons(), presetAttributify(), presetUno()],
      })
    ],
    server:{
      port: 8848,  // 应用端口
      host: "0.0.0.0", // 允许IP访问
      open: true,   // 运行是否自动打开浏览器
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: "http://127.0.0.1:9527",  //我的
          changeOrigin: true,
          rewrite: (path) => path.replace(
            new RegExp("^" + env.VITE_APP_BASE_API), // ^/dev-api
            env.VITE_APP_TARGET_BASE_API // ""
          ),
        }
      }
    },
    resolve: {
      alias: {
        "@": "/src",
      },
    },
  };
});
